package com.example.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.config.ResponseBean;
import com.example.config.UnicomResponseEnums;
import com.example.sys.entity.User;
import com.example.sys.entity.UserRole;
import com.example.sys.service.LogininforService;
import com.example.sys.service.RoleService;
import com.example.sys.service.UserRoleService;
import com.example.sys.service.UserService;
import com.example.sys.vo.UserVo;
import com.example.util.HutoolUtils;
import com.example.util.NetworkUtil;
import com.example.util.SqlUtils;
import com.example.util.UserRegisteAndLogin;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.time.LocalDateTime;
import java.util.List;


@RestController
public class LoginController{

    @Autowired
    private UserService userService;

    @Autowired
    private LogininforService logininforService;

    @Autowired
    private RoleService roleService;

    @Autowired
    private UserRoleService userRoleService;


    /**
     * GET请求，返回login页面
     * @return
     */
    @GetMapping("/login")
    public String login(){
        return "login";
    }

    /**
     * 前后端分离，获取参数必须加入@RequestBody
     * @param user 获取登陆帐号与密码
     * @return
     */
    @PostMapping("/login")
    @ResponseBody
    public ResponseBean<UnicomResponseEnums> postLogin(@RequestBody UserVo userVo){
        //用户信息bean
        System.out.println(userVo.getUserName());
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(userVo.getUserName(), userVo.getPassword());
        try {
            //验证
            subject.login(token);
            //登陆成功后的处理逻辑：
            User user = new User();
            user.setLoginDate(LocalDateTime.now());
            user.setToken(new HutoolUtils().getToken(64));
            User user1=userService.findUserByUserName(userVo.getUserName());
            user.setUserId(user1.getUserId());
            userService.updateById(user);

            //记录登录信息
//            setLogininfor(userVo,"登陆成功");
            logininforService.save(SqlUtils.setLogininfor(userVo, "登陆成功"));
            System.out.println("登陆成功");
            return new ResponseBean(true,user, UnicomResponseEnums.SUCCESS_OPTION);
        } catch (Exception e) {
            //登陆失败后的处理逻辑：
            logininforService.save(SqlUtils.setLogininfor(userVo, "登陆失败"));
            ResponseBean responseBean = new ResponseBean(false, UnicomResponseEnums.NOT_MATCH);
            System.out.println(responseBean);
            return responseBean;
        }
    }



    /**
     * 注册，返回注册页面
     * @return
     */
    @GetMapping("/userInfo/register")
    public String register(){
        return "/register";
    }


    /**
     *  注册页面
     * @param user
     * @param request
     * @param response
     * @param model
     * @return
     * @throws Exception
     */
    @PostMapping("/userInfo/register")
    public ResponseBean<UnicomResponseEnums> register(@RequestBody @Valid User user, HttpServletRequest request, HttpServletResponse response, Model model) throws Exception {
//      客户端IP地址
        String str = NetworkUtil.getIP(request);
//      登陆IP
        if (str != null) user.setLoginIp(str);
        user.setLoginDate(LocalDateTime.now());

        if (user.getUserName() != null) {

            String[] strs =getSaltPassword(user);
//          将用户名与密码进行计算得出盐值、密文
            user.setSalt(strs[1]);
            user.setPassword(strs[0]);
//          向数据库写入
            userService.save(user);

//            给新用户加入到默认权限组中
            QueryWrapper userQuery = new QueryWrapper();
            userQuery.eq("user_name", user.getUserName());
            Long userId=userService.getOne(userQuery).getUserId();
            QueryWrapper roleQuery = new QueryWrapper();
            roleQuery.eq("is_default", "0");
            Long roleId = roleService.getOne(roleQuery).getRoleId();
            UserRole userRole = new UserRole();
            userRole.setUserId(userId);
            userRole.setRoleId(roleId);
            userRoleService.save(userRole);

            return new ResponseBean(true,user, UnicomResponseEnums.SUCCESS_OPTION);
        }
        return new ResponseBean(true,UnicomResponseEnums.REGISTER_ERROR);
    }


    /**
     * 权限错误页面
     * @return
     */
    @RequestMapping("/403")
    public String unauthorizedRole() {
        System.out.println("------没有权限-------");
        return "403";
    }


    /**
     * 盐值、密文
     * @param user
     * @return
     */
    private String[] getSaltPassword(User user) {
        // 获取用户名与密码
        return UserRegisteAndLogin.encryptPassword(user.getUserName(), user.getPassword());
    }

    /**
     * 重置用户token
     * 每周设置一次更新token
     * @return
     */
    @RequestMapping("/userInfo/resetToken")
    public ResponseBean<UnicomResponseEnums> resetToken(){
        List<User> list=userService.list();
        System.out.println(list);
        for (User user:list) {
            user.setToken(new HutoolUtils().getToken(64));
        }
        System.out.println(list);
        userService.updateBatchById(list);
        return new ResponseBean(true, UnicomResponseEnums.SUCCESS_OPTION);
    }

}
